package per.chao.mqtt.domain.protocol.disconnect;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import per.chao.mqtt.domain.protocol.BaseProtocolHandler;
import per.chao.mqtt.domain.repo.PubRelMessageRepo;
import per.chao.mqtt.domain.repo.PublishMessageRepo;
import per.chao.mqtt.domain.repo.SessionRepo;
import per.chao.mqtt.domain.repo.SubscribeMessageRepo;
import per.chao.mqtt.domain.shared.store.SessionStore;

/**
 * Description:
 *
 * @author W.Chao
 * @date 2021/6/19 23:05
 **/
@Component
@Slf4j
public class DisConnect extends BaseProtocolHandler {
	@Autowired
	private SessionRepo sessionRepo;
	@Autowired
	private SubscribeMessageRepo subscribeRepo;
	@Autowired
	private PublishMessageRepo publishRepo;
	@Autowired
	private PubRelMessageRepo pubRelRepo;

	@Override
	public void handleMessage(Channel channel, Object msg) {
		String clientId = (String) channel.attr(AttributeKey.valueOf("clientId")).get();
		SessionStore sessionStore = sessionRepo.get(clientId);
		if (sessionStore != null && sessionStore.isCleanSession()) {
			subscribeRepo.remove(clientId);
			publishRepo.remove(clientId);
			pubRelRepo.remove(clientId);
		}

		Boolean cleanSession = sessionStore == null ? null : sessionStore.isCleanSession();
		log.info("DISCONNECT - clientId: {}, cleanSession: {}", clientId, cleanSession);
		sessionRepo.remove(clientId);
		channel.close();
	}
}
